package com.qt.manager.oj;

import com.qt.dispatcher.JudgeDispatcher;
import com.qt.exception.StatusFailException;
import com.qt.mapper.JudgeMapper;
import com.qt.pojo.dto.SubmitJudgeDTO;
import com.qt.pojo.entity.judge.Judge;
import com.qt.shiro.UserProfile;
import com.qt.utils.Constants;
import com.qt.utils.IpUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * @author pgw
 * @version 1.0
 * @description
 * @date Create by 2023/9/25 16:10
 */
@Component
public class JudgeManager {

//   @Autowired
//   private JudgeVaildator judgeVaildator;

   @Autowired
   private JudgeDispatcher judgeDispatcher;

   @Autowired
   private JudgeMapper judgeMapper;

   /**
    * 核心判题
    * @param submitJudgeDto
    * @return
    */
   public Judge submitProblemJudge(SubmitJudgeDTO submitJudgeDto) throws StatusFailException {
//        judgeVaildator.validateSubmissionInfo(submitJudgeDto);

//      UserProfile userRolesVo = (UserProfile) SecurityUtils.getSubject().getPrincipal();
       UserProfile userRolesVo  = new UserProfile();
      userRolesVo .setUserId("1");
      userRolesVo .setUsername("pgw");
      //判断是否为比赛提交
      boolean isContestSubmit =  submitJudgeDto.getContestId() != null ?  true : false;
      HttpServletRequest request = ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getRequest();
      // 将提交先写入数据库，准备调用判题服务器
      Judge judge = new Judge();
      judge.setProblemId(submitJudgeDto.getProblemId())
              .setDisplayProblemId(submitJudgeDto.getDisplayProblemId())
               .setCode(submitJudgeDto.getCode())
              .setContestId(submitJudgeDto.getContestId())
              .setLanguage(submitJudgeDto.getLanguage())
              .setLength(submitJudgeDto.getCode().length())
              .setUserId(userRolesVo.getUserId())
              .setUsername(userRolesVo.getUsername())
              .setStatus(Constants.Judge.STATUS_PENDING.getStatus()) // 开始进入判题队列
              .setSubmitTime(new Date())
              .setIp(IpUtils.getUserIpAddr(request));
     judgeMapper.insert(judge);
      //对比赛id、提交时间进行判断
      if(isContestSubmit){

      }else{

      }
      judgeDispatcher.sendTask(judge.getId() , judge.getProblemId() , isContestSubmit);

      return judge;
   }

}
